import pAddDisabled from '@/images/cart/add-disabled.png';
import pAdd from '@/images/cart/add.png';
import pSubDisabled from '@/images/cart/sub-disabled.png';
import pSub from '@/images/cart/sub.png';
import { Image, Input, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React from 'react';
import { ActivityType } from '../../constants';
import './index.scss';

const AddSubtract = ({ product, value, onChange }) => {
  const { inventoryQuantity, activityType, activityLimit } = product ?? {};
  const iq = parseInt(`${inventoryQuantity}`, 10);
  const al = parseInt(`${activityLimit}`, 10);

  const checkInventory = (input) => {
    if (input >= iq) {
      Taro.showToast({
        title: '数量修改失败，超出库存！',
        icon: 'none',
        mask: false,
        duration: 1500,
      });

      return false;
    }

    return true;
  };

  const noticeOff = (input) => {
    if (activityType === ActivityType.off && activityLimit > 0 && input > al) {
      Taro.showToast({
        title: '该折扣商品限购' + activityLimit + '份,超过' + activityLimit + '份恢复原价',
        icon: 'none',
        mask: false,
        duration: 1500,
      });

      return false;
    }

    return true;
  };

  const handleSub = () => {
    if (value === 1) {
      return;
    }

    if (value <= 1) {
      onChange(1);
    } else {
      onChange(value - 1);
    }
  };

  const handleAdd = () => {
    const v = value + 1;

    const isValid = checkInventory(v);

    if (isValid) {
      noticeOff(v);

      onChange(value + 1);
    }
  };

  const handleInput = (e) => {
    const v = parseInt(`${e.detail.value || '1'}`, 10);
    const isValid = checkInventory(v);

    if (!isValid) {
      onChange(iq);
    } else if (v <= 1) {
      // 如果 value 刚好也是1, 不会触发更新, 用onChange + setTimeout 来变更两次触发更新
      onChange(v);
      setTimeout(() => {
        onChange(1);
      }, 0);
    } else {
      noticeOff(v);
      onChange(v);
    }
  };

  return (
    <View className="addSubtract">
      <View className="sub" onClick={handleSub}>
        {value <= 1 ? (
          <Image src={pSubDisabled} className="img" />
        ) : (
          <Image src={pSub} className="img" />
        )}
      </View>
      <View className="placeholder"></View>
      <Input
        className="number"
        maxlength={4}
        value={value}
        placeholderStyle="color:#E5E5E5"
        onBlur={handleInput}
      ></Input>
      <View className="placeholder"></View>
      <View className="add" onClick={handleAdd}>
        {value >= iq ? (
          <Image src={pAddDisabled} className="img" />
        ) : (
          <Image src={pAdd} className="img" />
        )}
      </View>
    </View>
  );
};

export default AddSubtract;
